package com.stone.serverless.web;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.text.StrPool;
import com.stone.serverless.sdk.utils.InvokeUtil;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

/**
 * @Description: TODO
 * @Author: MECHREVO
 * @Date: 2022/1/25 18:47
 * @Version: 1.0.0
 */
public class RpcServiceHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {

        Annotation[] parameterAnnotations = parameter.getParameterAnnotations();
        return parameterAnnotations.length == 0;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Class<?> parameterType = parameter.getParameterType();

        int parameterIndex = parameter.getParameterIndex();
        String parameter1 = webRequest.getParameter("arg" + parameterIndex);
        Type genericParameterType = parameter.getGenericParameterType();
        if (CharSequenceUtil.isNotBlank(parameter1)) {
            InvokeUtil.TypeInfo typeInfo = InvokeUtil.getTypeInfo(parameterType, genericParameterType, CharSequenceUtil.concat(true, parameterType.getName(), StrPool.UNDERLINE, genericParameterType.getTypeName()));
            Object transfer = InvokeUtil.transfer(parameter1, typeInfo);
            return transfer;
        }
        return null;
    }
}
